'use strict';
/**
 * Created by FreezeSoul on 2015/10/18.
 */
define([
        'angular',
        'app/modules/dataset/define',
        'app/modules/dataset/services/dataset',
        'app/modules/dataset/controllers/dataset-param',
        'app/modules/source/services/source'
    ],
    function (angular) {
        angular.module('ad.dataset')
            .controller('adDataSetServiceController', ['$scope', '$stateParams', '$uibModal', '_', 'Notification', 'adDataSetService', 'adSourceService'
                , function ($scope, $stateParams, $uibModal, _, Notification, dataSetService, dataSouceService) {

                    $scope.dataColumns = [];

                    $scope.executeData = [];

                    $scope.tables = [];

                    if (!$scope.dataset_defines.DataServiceMeta.QueryUrlAddress) {
                        $scope.dataset_defines.DataServiceMeta.QueryUrlAddress = '';
                    }
                    if (!$scope.dataset_defines.DataServiceMeta.QueryUrlFunction) {
                        $scope.dataset_defines.DataServiceMeta.QueryUrlFunction = 'function parse(data){var input = JSON.parse(data); return JSON.stringify(input);}';
                    }
                    if (!$scope.dataset_defines.DataServiceMeta.QueryUrlParams) {
                        $scope.dataset_defines.DataServiceMeta.QueryUrlParams = [];
                    }

                    if ($scope.$stateParams.datasetid == 0) {
                        $scope.dataset_defines.DataServiceMeta.QueryUrlAddress = '';
                        $scope.dataset_defines.DataServiceMeta.QueryUrlFunction = 'function parse(data){var input = JSON.parse(data); return JSON.stringify(input);}';
                        $scope.dataset_defines.DataServiceMeta.QueryUrlParams = [];
                    } else {
                        if (angular.isArray($scope.dataset_defines.DataColumnsMap)) {
                            _.each($scope.dataset_defines.DataColumnsMap, function (map) {
                                if (map.Column && $scope.dataColumns.indexOf(map.Column) == -1) {
                                    $scope.dataColumns.push(map.Column);
                                }
                            });
                        }
                    }


                    $scope.aceLoaded = function (_editor) {
                        $scope.sqlEditor = _editor;
                        $scope.aceSession = _editor.getSession();

                        _editor.session.setMode("ace/mode/javascript");
                        _editor.setTheme("ace/theme/dreamweaver");
                        _editor.$blockScrolling = Infinity;

                        _editor.setOptions({
                            enableBasicAutocompletion: true,
                            enableLiveAutocompletion: true,
                            enableSnippets: false,
                            fontSize: 16,
                            wrap: true
                        });

                        $scope.$on('$destroy', function () {
                            _editor.destroy();
                            _editor.container.remove();
                        });

                        if ($scope.dataset_defines.DataServiceMeta.QueryUrlFunction !== undefined)
                            _editor.setValue($scope.dataset_defines.DataServiceMeta.QueryUrlFunction);
                    };

                    $scope.aceChanged = function () {
                        $scope.dataset_defines.DataServiceMeta.QueryUrlFunction = $scope.aceSession.getDocument().getValue();
                    };


                    $scope.serviceChanged = function () {
                    };

                    $scope.executeService = function () {
                        var url = $scope.dataset_defines.DataServiceMeta.QueryUrlAddress;
                        if (!url) return;
                        var fun = $scope.dataset_defines.DataServiceMeta.QueryUrlFunction;
                        if (!fun) return;
                        $scope.sqlEditor.setValue(fun);
                        var params = $scope.dataset_defines.DataServiceMeta.QueryUrlParams;

                        dataSouceService.invokeService(url, fun, params).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.executeData = obj.data.data;
                                $scope.dataColumns = obj.data.columns;
                                Notification.success('数据加载成功！');
                            } else {
                                Notification.error('数据加载失败，请检查参数设置！');
                            }
                        });
                    };

                    $scope.paramsSet = function () {
                        var paramsList = dataSetService.patternParams($scope.dataset_defines.DataServiceMeta.QueryUrlAddress);
                        if (paramsList.length > 0 && $scope.dataset_defines.DataServiceMeta.QueryUrlParams.length === 0) {
                            $scope.dataset_defines.DataServiceMeta.QueryUrlParams = _.map(paramsList, function (p) {
                                return {
                                    ParamName: p,
                                    DataType: '',
                                    DefaultValue: ''
                                }
                            });
                        }

                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/dataset/views/dataset-param.tpl.html',
                            controller: 'adDateSetParamController',
                            size: 'lg',
                            resolve: {
                                items: function () {
                                    return $scope.dataset_defines.DataServiceMeta.QueryUrlParams;
                                }
                            }
                        });

                        modalInstance.result.then(function (items) {
                            _.each(items, function (item) {
                                if (item.DefaultValue === undefined) {
                                    item.DefaultValue = "";
                                }
                            });
                            $scope.dataset_defines.DataServiceMeta.QueryUrlParams = items;
                        }, function () {
                        });
                    };
                }]);
    });